<?php
/**
 * Created by PhpStorm.
 * User: Joel
 * Date: 2015-12-28
 * Time: 2:22 PM
 */

namespace waylaidwanderer\SteamCommunity\TradeOffers;

use waylaidwanderer\SteamCommunity\Helper;
use waylaidwanderer\SteamCommunity\SteamCommunity;
use waylaidwanderer\SteamCommunity\TradeOffers\Trade\TradeAsset;
use waylaidwanderer\SteamCommunity\TradeOffers\Trade\TradeUser;
use App\Service\LogService;
use App\Model\BotsModel;

class Trade implements \JsonSerializable
{
    private $newVersion = true;
    private $version = 1;
    private $me;
    private $them;
    private $steamCommunity;
    private $accountId;

    private $error = '';
    private $message = '';

    public function __construct(SteamCommunity $steamCommunity, $accountId)
    {
        $this->me = new TradeUser($this);
        $this->them = new TradeUser($this);
        $this->steamCommunity = $steamCommunity;
        $this->accountId = $accountId;
    }

    public function jsonSerialize()
    {
        return [
            'newversion' => $this->newVersion,
            'version' => $this->version,
            'me' => $this->me,
            'them' => $this->them
        ];
    }

    public function addMyItem($appId, $contextId, $assetId, $amount = 1)
    {
        $asset = new TradeAsset($appId, $contextId, $assetId, $amount);
        return $this->addMyItemByAsset($asset);
    }

    public function addMyItemByAsset(TradeAsset $asset)
    {
        return $this->me->addItem($asset);
    }

    public function addOtherItem($appId, $contextId, $assetId, $amount = 1)
    {
        $asset = new TradeAsset($appId, $contextId, $assetId, $amount);
        return $this->addOtherItemByAsset($asset);
    }

    public function addOtherItemByAsset(TradeAsset $asset)
    {
        return $this->them->addItem($asset);
    }

    public function sendWithToken($token)
    {
        return $this->send($token);
    }
	
    public function send($token = '')
    {
    	try {
	        $url = 'https://steamcommunity.com/tradeoffer/new/send';
	        $referer = 'https://steamcommunity.com/tradeoffer/new/' .
	            '?partner=' . $this->accountId . ($token ? '&token=' . $token : '');
	        $params = [
	            'sessionid' => $this->steamCommunity->getSessionId(),
	            'serverid' => '1',
	            'partner' => Helper::toCommunityID($this->accountId),
	            'tradeoffermessage' => $this->message,
	            'json_tradeoffer' => json_encode($this),
	            'trade_offer_create_params' => (empty($token) ? "{}" : json_encode([
	                'trade_offer_access_token' => $token
	            ]))
	        ];
	     	$response = $this->steamCommunity->cURL($url, $referer, $params);
	        $json = json_decode($response, true);
	        if (is_null($json)) {
	        	$botSteamId = $this->steamCommunity->getSteamId();
	        	$bot = BotsModel::where(['steam_id'=>$botSteamId])->first();
	        	LogService::getInstance()->addActionLog('createTradeOffer', 0,$botSteamId  ,'botId is '. $bot['id'].'Empty response');
	            $this->error = 'Empty response';
	            return 'relogin';
	        } else {
	            if (isset($json['tradeofferid'])) {
	                return $json['tradeofferid'];
	            } else {
	            	$steamId = Helper::toCommunityID($this->accountId);
	            	$botSteamId = $this->steamCommunity->getSteamId();
	            	$bot = BotsModel::where(['steam_id'=>$botSteamId])->first();
	            	LogService::getInstance()->addActionLog('createTradeOffer', 0,$steamId  ,'botId is '. $bot['id'].$response);
	                $this->error = $json['strError'];
	                if(strpos($this->error,'15') !== false){
	                	//你的物品背包已满 无法取回
	                	return 'full_package';
	                }elseif(strpos($this->error,'26') !== false){
	                	//交易报价物品已被取回
	                	return 'no_exist_item';
	                }elseif(strpos($this->error,'We were unable to contact') !== false){
	                	//steam 接口暂时不能相应
	                	return 'steam_no_response';
	                }elseif(strpos($this->error,'More information will be') !== false){
	                	//无法进行交易。亮光光的光头 将在邀请您交易时看到更多信息。
	                	return 'can_send_trade';
	                }elseif(strpos($this->error,'have too many outstanding trade offers') !== false){
	                	return 'too_maney_trade';
	                	// 请保证你的物品尽量不要分批次取出，导致发送报价过多，请先处理玩已发送的报价
	                }elseif(strpos($this->error,'This trade cannot be completed because it would exceed the maximum number') !== false) {
                        return 'too_maney_trade';
                    }
	                return 'relogin';
	            }
	        }
	       } catch (\Exception $e) {
		       	$steamId = Helper::toCommunityID($this->accountId);
		       	$botSteamId = $this->steamCommunity->getSteamId();
		       	$bot = BotsModel::where(['steam_id'=>$botSteamId])->first();
		       	LogService::getInstance()->addActionLog('createTradeOffer', 0,$steamId  ,'botId is '. $bot['id'].$e->getMessage());
	       		 return 'relogin';
	       }
    }

    /**
     * @return int
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * @param int $version
     */
    public function setVersion($version)
    {
        $this->version = $version;
    }

    /**
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * @param string $message
     */
    public function setMessage($message)
    {
        $this->message = $message;
    }
}
